package org.mclll.xwangplugin.questTracking.questGoal;

import me.pikamug.quests.events.quester.BukkitQuesterPostUpdateObjectiveEvent;
import me.pikamug.quests.quests.components.BukkitObjective;
import me.pikamug.quests.quests.components.Stage;
import net.md_5.bungee.api.ChatColor;
import org.bukkit.entity.EntityType;
import org.bukkit.scoreboard.Objective;
import org.jetbrains.annotations.NotNull;
import org.mclll.xwangplugin.questTracking.persistence.Persistence;
import org.mclll.xwangplugin.util.GetChineseNameUtil;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author: geduo
 * @date: 2023/10/13 13:41
 */
public class MobKillQuestTrack {

    private static final String FORMAT_PREFIX = "击杀%s";
    private static final String LINE_FORMAT = FORMAT_PREFIX + " (%d/%d)";

    public static void questTracking(Objective context, Integer line, Stage questsStage) {
        LinkedList<EntityType> mobsToKill = (LinkedList<EntityType>) questsStage.getMobsToKill();
        if (mobsToKill.isEmpty()) {
            return;
        }
        LinkedList<Integer> mobNumToKill = questsStage.getMobNumToKill();
        for (int i = 0; i < mobsToKill.size(); i++) {
            EntityType entityType = mobsToKill.get(i);
            Integer killCount = mobNumToKill.get(i);
            context.getScore(getGoalFormat(entityType, 0, killCount))
                    .setScore(line--);
        }

    }

    @NotNull
    public static String getGoalFormat(EntityType entityType, Integer progress, Integer killCount) {
        return ChatColor.YELLOW + String.format(LINE_FORMAT, GetChineseNameUtil.get(entityType), progress, killCount);
    }
    @NotNull
    public static String getFinishFormat(EntityType entityType) {
        return ChatColor.GRAY + String.format(FORMAT_PREFIX, GetChineseNameUtil.get(entityType)) + " (✓)";
    }

    public static void goalFinish(BukkitQuesterPostUpdateObjectiveEvent event, List<Persistence.SerializeScore> scoreboard) {
        BukkitObjective questObj = (BukkitObjective) event.getObjective();
        EntityType killMob = (EntityType) questObj.getGoalObject();
        String chineseName = GetChineseNameUtil.get(killMob);
        Map<String, Persistence.SerializeScore> collect = scoreboard.stream()
                .collect(Collectors.toMap(item -> item.getName().split(" \\(")[0].substring(4), obj -> obj));

        Persistence.SerializeScore score = collect.get(chineseName);
        if (score == null) {
            return;
        }
        int amount = questObj.getGoal() - questObj.getProgress();
        if (amount == 0) {
            score.setName(getFinishFormat(killMob));
            score.setValue(scoreboard.get(scoreboard.size() - 1).getValue() - 1);
        } else {
            score.setName(getGoalFormat(killMob, questObj.getProgress(), questObj.getGoal()));
        }
    }


}
